using System;
using System.Collections.Generic;
using UnityEngine;
using WorldMapBase.Tile.Pool;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Object = UnityEngine.Object;

namespace Yoozoo.Gameplay.RTS
{
    public class RTSModelManager
    {
        //public Dictionary<string, TRtsSoldierModelConfig> SoldierModelPathDic;
        private static ResLoader _resLoader;
        private GameObject arrowObject;

        private string[] heroModelPath =
        {
            @"Prefabs/Character/Hero/Mc_Moto_Lod1_inst.prefab"
        };

        private bool isDisposed = false;
        private Dictionary<int, RtsInstanceModelPool> m_dic = new Dictionary<int, RtsInstanceModelPool>();
        private Dictionary<string, RtsInstanceModelPool> soldierDic = new Dictionary<string, RtsInstanceModelPool>();
        public static Dictionary<string,int> modelNameToIndex = new Dictionary<string, int>();
        private GameObject m_object;

        private Action onInitOver;


        public RTSModelManager(ResLoader resLoader)
        {
            _resLoader = resLoader;
        }

        public void Init(Transform parent)
        {
            if (m_object != null)
            {
                Object.DestroyImmediate(m_object);
            }

            m_object = new GameObject("[RTSModelManager]");
            m_object.SetActive(false);
            m_object.transform.SetParent(parent);
        }

        public void LoadSoldiers(Action onInitOver)
        {
            isDisposed = false;
            this.onInitOver = onInitOver;
            foreach (var item in m_dic)
            {
                item.Value.StartLoading();
            }
        }

        public void RemoveModel(IModel model)
        {
            ModelInstaning modelInstaning = model as ModelInstaning;
            if (modelInstaning)
            {
                RtsInstanceModelPool modelPool;
                if (m_dic.TryGetValue(modelInstaning.poolKey,out modelPool))
                {
                    modelPool.RecoverItem(modelInstaning);
                }
            }
        }

        public IModel GetModel(int index)
        {
            if (m_dic.ContainsKey(index))
            {
                return m_dic[index].GetItem();
            }

            return null;
        }

        public IModel GetModel(string modelName)
        {
            if (soldierDic.ContainsKey(modelName))
            {
                return soldierDic[modelName].GetItem();
            }

            return null;
        }

        public static int GetIndexByModelName(string modelName)
        {
            if (modelNameToIndex.TryGetValue(modelName, out var id))
            {
                return id;
            }

            return 0;
        }

        public void Dispose()
        {
            _resLoader = null;
            isDisposed = true;
            foreach (var item in m_dic.Values)
            {
                item.Destroy();
            }
            m_dic.Clear();
            soldierDic.Clear();
            modelNameToIndex.Clear();
        }

        private void CheckOver()
        {
            if (isDisposed)
            {
                return;
            }

            foreach (var item in m_dic.Values)
            {
                if (!item.IsReady())
                {
                    return;
                }
            }
            Shader.SetGlobalColor("_ShadowColor", new Color(0, 0, 0, 0.7f));
            Shader.SetGlobalVector("_ShadowOffset", new Vector4(0.46f, -0.7f, 0, 0));
            Shader.SetGlobalVector("_LightDir", new Vector4(-1000, 1000, 250, 1));
            Shader.SetGlobalColor("_LightColor", Color.white);

            Debug.Log("load soldier complete");
            if (onInitOver != null)
            {
                onInitOver();
            }
        }

        public void LoadRtsSoldierJsonConfig(Action action = null)
        {
            if (!BattleUtils.IsSprite)
            {
                InitPool();
            }
            action?.Invoke();
            //_resLoader.Add2Load("Assets/ResourcesAssets/Config/RTSScriptConfig/rts_soldier_model_config.json",
            //    (success, name, asset) =>
            //    {
            //        if (success)
            //        {
            //            var json = asset as TextAsset;
            //            if (json)
            //            {
            //                var jsonData = JsonMapper.ToObject(json.text);

            //                if (jsonData != null)
            //                {
            //                    if (SoldierModelPathDic == null)
            //                    {
            //                        SoldierModelPathDic = new Dictionary<string, TRtsSoldierModelConfig>(jsonData.Count);
            //                    }
            //                    SoldierModelPathDic.Clear();
            //                    for (int i = 0; i < jsonData.Count; i++)
            //                    {
            //                        JsonMapper.RegisterExporter<float>((obj, writer) =>
            //                            writer.Write(Convert.ToDouble(obj)));
            //                        JsonMapper.RegisterImporter<double, float>(input => Convert.ToSingle(input));
            //                        var resourceConfig = JsonMapper.ToObject<TRtsSoldierModelConfig>(jsonData[i].ToJson());
            //                        SoldierModelPathDic.Add(resourceConfig.id, resourceConfig);
            //                        modelNameToIndex.Add(resourceConfig.id, i);
            //                    }
            //                }
            //                modelNameToIndex.Add("gta_commander", 100);
                            
            //            }
            //        }
            //        else
            //        {
            //            Debug.LogError("load Asset failed : {0} " + name);
            //        }
            //    }).Load();
        }

        private void InitPool()
        {
            var dic = ArmyManager.Instance.GetRtsResourceManager()?.GetSoldierModelInfoDic();
            if (dic!=null)
            {
                RtsInstanceModelPool pool;

                var enumerator = dic.GetEnumerator();
                int i = 0;
                while (enumerator.MoveNext())
                {
                    int key = i;
                    pool = new RtsInstanceModelPool(250, 10, _resLoader, key, enumerator.Current.Value.modelPath, m_object.transform, CheckOver);
                    soldierDic.Add(enumerator.Current.Key, pool);
                    m_dic.Add(key, pool);
                    i++;
                }
                enumerator.Dispose();
                //100写死为英雄的摩托兵
                pool = new RtsInstanceModelPool(250, 10, _resLoader, 100, heroModelPath[0], m_object.transform, CheckOver);
                m_dic.Add(100, pool);
            }
        }
    }
}   
